package com.example.androidproject.service;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.example.androidproject.service.config.MusicManager;
import com.hyg.common.utils.FileUtils;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MusicService extends Service {
    private final String musicsPath = "/sdcard/Music";
    private MediaPlayer mediaPlayer;
    private ArrayList<String> musicPaths = new ArrayList<>();
    private int musicIndex = 0;
    private String currentMusicPath;
    private Disposable timerDisposable;//监听整个APP有没有完全退出
    private boolean isStartPlaying = false; //初始化获取音乐时间长度，但不播放

    private MusicClientBinder mBinder = new MusicClientBinder();

    //用于Activity和service通讯
    public class MusicClientBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        // 初始化音乐资源
        getMusicsPath();
        super.onCreate();
        if(musicPaths.size() > 0){
            playSong(currentMusicPath);
            initMusicTimerListener();
        }
    }

    @Override
    public void onDestroy() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if(timerDisposable != null){
            timerDisposable.dispose();
        }
        super.onDestroy();
    }

    public MediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }

    private void getMusicsPath() {
        File file = new File(musicsPath);
        FileUtils.createOrExistsDir(file);
        File[]files = file.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith(".mp3")){
                    return true;
                }
                return false;
            }
        });
        if (null == files || files.length < 1){
            currentMusicPath = " no music file in /sdcard/Music!";
            return;
        }
        for (File f : files) {
            musicPaths.add(f.getAbsolutePath());
        }
        currentMusicPath = musicPaths.get(musicIndex);
    }

    private void playSong(String soundUrl){
        if(TextUtils.isEmpty(soundUrl)){
            playNext();
            return;
        }
        try {
            if(mediaPlayer == null) {
                mediaPlayer = new MediaPlayer();
            }
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.setDataSource(soundUrl);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.prepareAsync();

            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    onSongChange();
                    if(isStartPlaying){
                        startPlay();
                    }
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    playNext();
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    return false;
                }
            });
        } catch (IOException e1) {
        }
    }

    MediaMetadataRetriever mmr = new MediaMetadataRetriever();
    private void onSongChange(){
        for(MusicManager.OnSongChangeListener listener : MusicManager.getInstance().getOnSongChangeListenerList()){
//            mmr.setDataSource(currentMusicPath);
//            String title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); //荷塘月色
//            String album = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); //专辑：我从草原来
//            String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); //凤凰传奇
//            byte[] pic = mmr.getEmbeddedPicture();  // 图片，可以通过bitmap = BitmapFactory.decodeByteArray(pic, 0, pic.length);转换为bitmap图片
//            String durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); //9172
//            int duration = 0;
//            try{
//                duration = Integer.parseInt(durationStr);
//            }catch (Exception e){}

            listener.changeSong(mediaPlayer.getDuration(),getMusicName(),"");
        }
    }

    public void stopPlay(){
        try {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
        }catch (Exception e){}
    }

    private void startPlay(){
        mediaPlayer.start();
        for(MusicManager.OnSongChangeListener listener : MusicManager.getInstance().getOnSongChangeListenerList()){
            listener.onStateChange(true);
        }
    }

    public void start(){
        if(musicPaths.size() == 0) return;
        isStartPlaying = true;
        if (mediaPlayer != null) {
            startPlay();
        }else {
            playSong(currentMusicPath);
        }
    }

    public void pause(){
        if(musicPaths.size() == 0) return;
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
        for(MusicManager.OnSongChangeListener listener : MusicManager.getInstance().getOnSongChangeListenerList()){
            listener.onStateChange(false);
        }
    }

    public void playNext(){
        if(musicPaths.size() == 0) return;
        musicIndex ++;
        if (musicIndex > musicPaths.size() - 1){
            musicIndex = 0;
        }
        currentMusicPath = musicPaths.get(musicIndex);
        playSong(currentMusicPath);
    }

    public void playBeforeMusic(){
        if(musicPaths.size() == 0) return;
        musicIndex--;
        if (musicIndex < 0){
            musicIndex = musicPaths.size()-1;
        }
        currentMusicPath = musicPaths.get(musicIndex);
        playSong(currentMusicPath);
    }

    public void playIndex(int musicIndex){
        if(musicPaths.size() == 0) return;
        if (musicIndex < 0 || musicIndex > musicPaths.size() - 1){
            musicIndex = 0;
        }
        this.musicIndex = musicIndex;
        currentMusicPath = musicPaths.get(musicIndex);
        playSong(currentMusicPath);
    }

    public boolean isStartPlaying(){
        return  mediaPlayer != null && mediaPlayer.isPlaying();
    }

    public String getMusicName(){
        if(TextUtils.isEmpty(currentMusicPath)) {}
        String name = new File(currentMusicPath).getName();
        if (TextUtils.isEmpty(name)){
            name = "no music finded in /sdcard/Music";
        }
        return name;
    }

    public ArrayList<String> getMusicPaths() {
        return musicPaths;
    }

    public void initMusicTimerListener() {
        if(timerDisposable == null || timerDisposable.isDisposed()){
            // initialDelay：首次执行任务延迟多少 period：定时任务时间间隔 unit：时间单位
            timerDisposable = Observable.interval(0, 500, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            if (musicPaths.size() > 0) {
                                for (MusicManager.OnSongChangeListener listener : MusicManager.getInstance().getOnSongChangeListenerList()) {
                                    int duration = 0;
                                    if (mediaPlayer.getDuration() > 0)
                                        duration = mediaPlayer.getDuration();
                                    int currentPosition = 0;
                                    if (mediaPlayer.getCurrentPosition() > 0)
                                        currentPosition = mediaPlayer.getCurrentPosition();
                                    listener.onProgress(duration, currentPosition);
                                }
                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {

                        }
                    });
        }
    }


}
